package com.ygnn.reggie.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ygnn.reggie.dto.DishDto;
import com.ygnn.reggie.entity.Dish;
import com.ygnn.reggie.entity.DishFlavor;
import com.ygnn.reggie.mapper.DishMapper;
import com.ygnn.reggie.service.DishFlavorService;
import com.ygnn.reggie.service.DishService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

//    新增菜品，同时插入口味
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
//        基本数据保存到dish表
        this.save(dishDto);
        Long id = dishDto.getId();

//        菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

//        遍历赋值
        flavors=flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());

//       保存
        dishFlavorService.saveBatch(flavors);

    }


//    根据id查询菜品和口味
    @Override
    public DishDto selectByIdWithFlavor(Long id) {

        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();
//      拷贝除了flavor外的数据
        BeanUtils.copyProperties(dish,dishDto);

//       查询flavor
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);

//        设置口味
        dishDto.setFlavors(list);
        return dishDto;
    }


//    更新菜品和口味
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishdto) {
//        1.更新dish表
        this.updateById(dishdto);
//        2.删除口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishdto.getId());
        dishFlavorService.remove(queryWrapper);

//        3.新增口味数据
        List<DishFlavor> flavors = dishdto.getFlavors();

//        遍历赋值
        flavors=flavors.stream().map((item)->{
            item.setDishId(dishdto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }


}
